import os.path
from django.forms.models import model_to_dict

# Create your views here.
from django.views.decorators.http import require_http_methods
from chat.models import User, Admin, Message
from chat.utils import getToken
from chat_django.settings import BASE_DIR

from django.shortcuts import render
import json
import threading
from dwebsocket.decorators import accept_websocket, require_websocket
from django.http import JsonResponse, HttpResponse
from chat.models import User
import os

# 存储连接websocket的用户
clients = {}
# 记录连接人数   其实没什么卵用  = =
count = 0


@accept_websocket
def websocket_link(request):
    '连接websocket'
    global count
    # 获取连接
    returnData = {
        'type': 'error',
        'data': {}
    }
    if request.is_websocket():
        lock = threading.RLock()  # rlock线程锁
        try:
            lock.acquire()  # 抢占资源
            user_id = request.GET.get('user_id')
            s = {}
            if clients.get(user_id) != None:
                # 连接信息  键 连接名  值：连接保存
                s[str(request.websocket)] = request.websocket
                # 已存在的连接信息继续增加
                clients[user_id].update(s)
            else:
                # 人数加1
                count = count + 1
                #  连接信息  键 连接名  值：连接保存
                s[str(request.websocket)] = request.websocket
                # 新增 用户  连接信息
                clients[user_id] = s
            for message in request.websocket:
                if message:
                    msg = json.loads(message)
                    if msg['type'] == 'client':
                        returnData['type'] = 'ok'
                        returnData['data'] = '欢迎{}用户'.format(user_id)
                        print('欢迎{}用户'.format(user_id))
                        request.websocket.send(json.dumps(returnData).encode('utf-8'))  # 发送消息到客户端
                    elif msg['type'] == 'sendMessage':
                        msg['user_id'] = user_id
                        send(str(msg['friend_id']), msg)
                    else:
                        continue
            else:
                request.websocket.send(json.dumps({'type': 'ok', 'data': []}).encode('utf-8'))
        finally:
            # 通过用户名找到 连接信息 再通过 连接信息 k 找到 v (k就是连接信息)
            clients.get(user_id).pop(str(request.websocket))
            # 释放锁
            lock.release()
    else:
        return HttpResponse(1)


# 发送消息
def websocketMsg(client, msg):
    import json
    # 因为一个账号会有多个页面打开 所以连接信息需要遍历
    for cli in client:
        'client客户端 ，msg消息'
        b1 = json.dumps(msg).encode('utf-8')
        client[cli].send(b1)


# 服务端发送消息
def send(username, data):
    'username:用户名 title：消息标题 data：消息内容，消息内容:ulr'
    # try:
    if clients.get(username,0):
        websocketMsg(clients[username], {'type': 'ok', 'data': data})
        # 根据业务需求 可有可无    数据做 持久化
        # messageLog = MessageLog(name=username, msg_title=title, msg=data, msg_url=url, is_required=0)

        flg = 1
    flg = -1
    # except BaseException:
    #     # messageLog = MessageLog(name=username, msg_title=title, msg=data, msg_url=url, is_required=1)
    #     pass
    # finally:
    #     pass


@require_http_methods(['GET'])
def index(req):
    return render(req, 'index.html')


# admin
@require_http_methods(["POST"])
def adminLogin(req):
    returnData = {
        'state': 0,
        'msg': '',
        'data': {},
        'extra': {}
    }
    params = json.loads(req.body.decode(req.encoding))
    admin_account = params.get('admin_account')
    admin_password = params.get('admin_password')
    adminData = Admin.objects.isExist(admin_account=admin_account, admin_password=admin_password)
    if not adminData:
        returnData['state'] = -1
        returnData['msg'] = "用户不存在"
    else:
        token = getToken(adminData.id)
        req.session['adminToken'] = adminData.id
        returnData['state'] = 200
        returnData['msg'] = "操作成功"
        returnData['data'] = model_to_dict(adminData)
        returnData['extra'] = {'token': token}
    return JsonResponse(returnData)


# User
@require_http_methods(["GET"])
def getUserList(req):
    returnData = {
        'state': 200,
        'msg': '',
        'data': {},
        'extra': {}
    }
    page = req.GET.get('page', 0)
    number = req.GET.get('number', 0)
    userData = User.objects.getList(page, number)
    if len(userData) == 0:
        returnData['msg'] = '没有相关数据'
    else:
        returnData['data'] = [model_to_dict(data) for data in userData]
    return JsonResponse(returnData)


@require_http_methods(["POST"])
def userAdd(req):
    returnData = {
        'state': 200,
        'msg': '',
        'data': {},
        'extra': {}
    }
    params = json.loads(req.body.decode(req.encoding))
    user_account = params.get('user_account', '')
    user_password = params.get('password', '')
    nickname = params.get('nickname', '')
    sex = params.get('sex', '')
    mobile_number = params.get('mobile_number', '')
    img = req.FILES['file']
    if img:
        head_img = os.path.join('static/image', img.name)
        filename = os.path.join(BASE_DIR, head_img)
        with open(filename, 'wb+') as destination:
            for chunk in img.chunks():
                destination.write(chunk)
    else:
        filename = ''
        head_img = 'static/img/default.png'
    is_registered = User.objects.isRegistered(user_account, mobile_number)
    if not is_registered:
        userData = User.objects.add(user_account=user_account, user_password=user_password, nickname=nickname,
                                    head_img=head_img, sex=sex, mobile_number=mobile_number)
        if not userData and filename:
            os.remove(filename)
            returnData['state'] = -1
            returnData['msg'] = '数据异常'
        else:
            returnData['data'] = model_to_dict(userData)
            returnData['msg'] = '新增成功'
            returnData['state'] = 200
    else:
        returnData['state'] = -1
        returnData['msg'] = '已注册，不可以重复注册'
    return JsonResponse(returnData)


@require_http_methods(["POST"])
def userEdit(req):
    returnData = {
        'state': 200,
        'msg': '',
        'data': {},
        'extra': {}
    }
    params = json.loads(req.body.decode(req.encoding))
    id = params.get('user_id')
    user_account = params.get('user_account', '')
    user_password = params.get('password', '')
    nickname = params.get('nickname', '')
    sex = params.get('sex', '')
    mobile_number = params.get('mobile_number', '')
    img = req.FILES['file']
    if img:
        head_img = os.path.join('static/image', img.name)
        filename = os.path.join(BASE_DIR, head_img)
        with open(filename, 'wb+') as destination:
            for chunk in img.chunks():
                destination.write(chunk)
    else:
        head_img = params.get('old_path')
    userData = User.objects.update(id=id, user_account=user_account, user_password=user_password, nickname=nickname,
                                   head_img=head_img, sex=sex, mobile_number=mobile_number)
    returnData['data'] = model_to_dict(userData)
    returnData['msg'] = '操作成功'
    return


@require_http_methods(["POST"])
def userLogin(req):
    returnData = {
        'state': 0,
        'msg': '',
        'data': {},
        'extra': {}
    }
    params = json.loads(req.body.decode(req.encoding))
    user_account = params.get('account', '')
    user_password = params.get('password', '')
    userData = User.objects.isExist(user_account=user_account, user_password=user_password)
    if userData:
        token = getToken(userData.id)
        req.session['userToken'] = userData.id
        req.session['user_id'] = userData.id
        returnData['state'] = 200
        returnData['msg'] = "操作成功"
        returnData['data'] = [model_to_dict(userData)]
        returnData['extra'] = {'token': token}
    else:
        returnData['state'] = -1
        returnData['msg'] = "用户不存在"
    return JsonResponse(returnData)


@require_http_methods(["GET"])
def searchUser(req):
    returnData = {
        'state': 200,
        'msg': '',
        'data': {},
        'extra': {}
    }
    keyword = req.GET.get('keyword')
    userData = User.objects.searchUser(keyword)
    returnData['data'] = model_to_dict(userData)
    returnData['msg'] = '操作成功'
    return JsonResponse(returnData)


@require_http_methods(['GET'])
def getUserAllById(req):
    returnData = {
        'state': 200,
        'msg': '',
        'data': model_to_dict(User.objects.get(req.GET.get('id'))),
        'extra': {}
    }
    return JsonResponse(returnData)


# Message
@require_http_methods(['GET'])
def getMessageList(req):
    returnData = {
        'state': 200,
        'msg': '',
        'data': {},
        'extra': {}
    }
    user_id = req.session.get('user_id')
    messageData = Message.objects.getLastMessageList(user_id)
    if messageData:
        data_ = []
        for data in messageData:
            UserData = User.objects.get(id=data.receive_user_id)
            data_.append({'id': data.receive_user_id, 'content': data.content, 'nickname': UserData.nickname,
                          'head_img': UserData.head_img})
        returnData['data'] = data_
        returnData['msg'] = '操作成功'
    else:
        returnData['msg'] = '暂无信息'
    return JsonResponse(returnData)


@require_http_methods(['GET'])
def getMessageByFriend(req):
    returnData = {
        'state': 200,
        'msg': '',
        'data': {},
        'extra': {}
    }
    user_id = req.session.get('user_id')
    friend_id = req.GET.get('friend_id')
    messageData = Message.objects.getMessageList(user_id, friend_id)
    if messageData:
        data_ = []
        for data in messageData:
            data_.append({'id': data.id, 'content': data.content, 'receive_user_id': data.receive_user_id,
                          'create_time': data.create_time, 'send_user_id': data.send_user_id})
        returnData['data'] = data_
        returnData['msg'] = '操作成功'
    else:
        returnData['msg'] = '暂无信息'
    return JsonResponse(returnData)


@require_http_methods(['POST'])
def saveMessage(req):
    returnData = {
        'state': 200,
        'msg': '',
        'data': {},
        'extra': {}
    }
    params = json.loads(req.body.decode(req.encoding))
    user_id = req.session.get('user_id')
    friend_id = params.get('friend_id')
    content = params.get('content')
    messageData = Message.objects.saveMessage(user_id, friend_id, content)
    if messageData:
        returnData['data'] = model_to_dict(messageData)
        returnData['msg'] = '新增成功'
        returnData['state'] = 200
    else:
        returnData['msg'] = '增加失败'
    return JsonResponse(returnData)


@require_http_methods(['GET'])
def getMessageCountByUser(req):
    returnData = {
        'state': 200,
        'msg': '',
        'data': {},
        'extra': {}
    }
    id_ = req.GET.get('id')
    time_start = req.GET.get('time_start')
    time_end = req.GET.get('time_end')
    messageData = Message.objects.getMessageCountByUser(id_, time_start, time_end)
    if messageData:
        returnData['data'] = [{'date': item['date'], 'count': item['count']} for item in messageData]
        returnData['msg'] = '查询成功'
        returnData['state'] = 200
    else:
        returnData['msg'] = '查询失败'
    return JsonResponse(returnData)
